<template>
  <div class="chat-container">
    <div class="content">
      <div v-show="model === 'chat'" class="right">
        <div ref="conversation" class="right-list" />
        <div ref="chat" class="right-content" />
        <div class="chat-info-wrapper">
          <div v-if="isConsumer && selectedConversation">
            <div class="title">客户资料</div>
            <el-tabs v-model="activeName" class="demo-tabs" @tab-change="handleChangeTab">
              <el-tab-pane v-for="(item, index) in housesInfoList" :key="index" :label="item.house.neighborhood"
                :name="index">
                <div class="title">房屋信息</div>
                <div class="info">
                  <div class="info-item">
                    <span class="label">地区：</span>
                    <span class="value">{{ item.house?.region }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">小区：</span>
                    <span class="value">{{ item.house?.neighborhood }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">面积：</span>
                    <span class="value">{{ item.house?.size || 0 }}平方</span>
                  </div>
                  <div class="info-item">
                    <span class="label">房屋结构：</span>
                    <DictLabel v-model="item.house.houseStructure" code="HouseStructure" size="small" />
                  </div>
                  <div class="info-item">
                    <span class="label">房屋类型：</span>
                    <DictLabel v-model="item.house.houseType" code="HouseType" size="small" />
                  </div>
                  <div class="info-item">
                    <span class="label">原始平面图：</span>
                    <image-preview v-for="file in JSON.parse(item.house?.planeGraphFile || '[]')" width="100px"
                      height="100px" :src="file.url"></image-preview>
                  </div>
                </div>
                <div class="title">设计机会</div>
                <div class="info">
                  <div class="info-item">
                    <span class="label">发布时间：</span>
                    <span class="value">{{ item.opportunityDesign?.publishTime }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">装修预算(元)：</span>
                    <span class="value">{{ item.opportunityDesign?.budget }}</span>
                  </div>
                </div>
                <div class="title">建材机会</div>
                <div class="info">
                  <div class="info-item">
                    <span class="label">品类名称：</span>
                    <span class="value">{{ item.opportunityMaterial?.categoryName }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">发布时间：</span>
                    <span class="value">{{ item.opportunityMaterial?.publishTime }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">预算(元)：</span>
                    <span class="value">{{ item.opportunityMaterial?.budget }}</span>
                  </div>
                </div>

                <div class="title">品类信息</div>
                <div class="info">
                  <div class="info-item">
                    <span class="label">品类名称：</span>
                    <span class="value">{{ item.categories?.name }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">预算金额(元)：</span>
                    <span class="value">{{ item.categories?.budgetAmount }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">已采购金额(元)：</span>
                    <span class="value">{{ item.categories?.purchasedAmount }}</span>
                  </div>
                </div>

                <div class="title">关联信息</div>
                <el-tabs v-model="activeContact" class="demo-tabs">
                  <el-tab-pane v-for="(element, i) in item.contacts || []" :key="i"
                    :label="getLabelByValue(UserTypeEnum, Number(element.userType))" :name="i">
                    <div class="info">
                      <div class="info-item">
                        <span class="label">地区：</span>
                        <span class="value">{{ item.house?.region }}</span>
                      </div>
                      <div class="info-item">
                        <span class="label">姓名：</span>
                        <span class="value">{{ element.name }}</span>
                      </div>
                      <div class="info-item">
                        <span class="label">电话：</span>
                        <span class="value">{{ element.mobile }}</span>
                      </div>
                      <div class="info-item">
                        <span class="label">装修公司：</span>
                        <span class="value">{{ element.decorationCompanyName }}</span>
                      </div>
                      <div class="info-item">
                        <span class="label">装修公司地址：</span>
                        <span class="value">{{ element.decorationAddress }}</span>
                      </div>
                    </div>
                  </el-tab-pane>
                </el-tabs>
              </el-tab-pane>
            </el-tabs>
          </div>
          <div v-if="!isConsumer && selectedConversation">
            <div class="title">商户资料</div>
            <div class="info">
              <div class="info-item">
                <span class="label">头像：</span>
                <image-preview width="100px" height="100px" :src="merchantInfo?.avatar"></image-preview>
              </div>
              <div class="info-item">
                <span class="label">用户昵称：</span>
                <span class="value">{{ merchantInfo?.nickname || "--" }}</span>
              </div>
              <div class="info-item">
                <span class="label">用户类型：</span>
                <span class="value">
                  {{ getLabelByValue(UserTypeEnum, Number(merchantInfo?.userType)) }}
                </span>
              </div>
              <div class="info-item">
                <span class="label">手机号：</span>
                <span class="value">
                  {{ merchantInfo?.mobile || "--" }}
                </span>
              </div>
              <div class="info-item">
                <span class="label">公司名称：</span>
                <span class="value">
                  {{ merchantInfo?.companyName || "--" }}
                </span>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div v-show="model === 'contact'" class="right">
        <div ref="contactList" class="right-list" />
        <div ref="contactInfo" class="right-content" />
      </div>
      <div v-if="model === 'collect'" class="collect">
        <div ref="collect" class="collectRight"></div>
      </div>
    </div>
  </div>
  <el-dialog v-model="dialogVisible" title="常用语" width="35%">
    <BasePageTable :table-data="phrasesList" :table-columns-data="tableColumnsData" :loading="tableLoading">
      <template #operation="{ row, name }">
        <el-button type="text" @click="handleSend(row.content)">发送</el-button>
      </template>
    </BasePageTable>
  </el-dialog>
</template>
<script setup lang="ts">
import { useNimStore } from "@/store/modules/nim";
const { initUiKit, login, requestPermission, sendMessageBySelectedConversation } = useNimStore();
import "@xkit-yx/im-kit-ui/es/style/css";
import { compile } from "jsx-web-compiler";
import "./iconfont.css";
import ImagePreview from "@/components/ImagePreview/index.vue";
import {
  ConversationContainer, // 会话列表组件
  ChatContainer, // 聊天（会话消息）组件
  ContactListContainer, // 通讯录——通讯录导航组件
  ContactInfoContainer, // 通讯录——通讯录详情组件，包含好友列表、群组列表以及黑名单列表
} from "@xkit-yx/im-kit-ui";
import { ActionRenderProps, ChatContainerProps } from "@xkit-yx/im-kit-ui/src/chat/Container";
import nimApi, { IMQueryParams } from "@/api/nim";
import { useRequest } from "@/hooks/useRequest";
import { getLabelByValue } from "../../../utils/enums";
import { UserTypeEnum } from "@/enums/system/UserEnum";
import { usePhrases } from "@/hooks/usePhrases";
import BasePageTable from "@/components/BasePageTable/index.vue";
const { phrasesList, tableLoading } = usePhrases();
const dialogVisible = ref(false);
const model = ref("chat");
const collect = ref();
const add = ref();
const empty = ref();
const search = ref();
const avatar = ref();
const chat = ref();
const conversation = ref();
const contactList = ref();
const contactInfo = ref();
const housesInfoList = ref([]);
const merchantInfo = ref({});
/*是否消费者*/
const isConsumer = ref(false);
/*当前活动的会话*/
const selectedConversation = ref("");
const activeName = ref(0);
const activeContact = ref(0);
let $uikit = initUiKit();

function handleChangeTab(val) {
  activeContact.value = 0;
}
async function getMerchantInfo(params: IMQueryParams): Promise<void> {
  const { res } = await useRequest(nimApi.getMerchantInfo, params);
  merchantInfo.value = res.value;
  console.log(res.value);
}

async function getConsumerInfo(params: IMQueryParams): Promise<void> {
  const { res } = await useRequest(nimApi.getConsumerInfo, params);
  housesInfoList.value = res.value;
}

function handleClick() {
  dialogVisible.value = true;
}

function handleSend(message) {
  dialogVisible.value = false;
  sendMessageBySelectedConversation(message);
}

onMounted(async () => {
  requestPermission();
  login();
  $uikit.render(
    ConversationContainer,
    {
      onConversationItemClick: (id) => {
        selectedConversation.value = id;
        housesInfoList.value = [];
        merchantInfo.value = {};
        const [senderId, receiverId] = id.split(/\|[^|]+\|/);
        const params: IMQueryParams = {
          senderId,
          receiverId,
        };
        //yzc开头的就是消费者 yzm就是商家
        isConsumer.value = receiverId.startsWith("yzc");
        activeName.value = 0;
        activeContact.value = 0;
        if (isConsumer.value) {
          getConsumerInfo(params);
        } else {
          getMerchantInfo(params);
        }
      },
    },
    conversation.value
  );
  $uikit.render(
    ChatContainer,
    {
      strangerTipVisible: false,
      // 以下是自定义渲染，用 compile 函数包裹 html 就可以了，注意 class 要写成 className
      // 安装并引入： import { compile } from "jsx-web-compiler";
      /*renderHeader: (conversation) => {
        console.log("conversation", conversation);
        return compile(`<div className="chat-header-wrap">123</div>`);
      },*/
      actions: [
        {
          action: "emoji",
        },
        {
          action: "sendImg",
        },
        {
          action: "sendFile",
        },
        {
          action: "phrases",
          visible: true,
          render: () => {
            return compile(
              `
            <div className="phrases-wrapper" onClick={context.click}>
            <span className="iconfont-dj icon-changyongyu icon"></span>
</div>
            `,
              { click: handleClick }
            );
          },
        },
        {
          action: "sendMsg",
        },
      ],
      p2pSettingActions: [],
      renderEmpty: () => compile('<div className="empty">暂无数据</div>'),
    } as ChatContainerProps,
    chat.value
  );
  $uikit.render(ContactListContainer, null, contactList.value);
  $uikit.render(
    ContactInfoContainer,
    {
      afterSendMsgClick: () => {
        model.value = "chat";
      },
      onGroupItemClick: () => {
        model.value = "chat";
      },
    },
    contactInfo.value
  );
});
const tableColumnsData = ref([
  {
    prop: "content",
    label: "常用语",
    showOverflowTooltip: true,
  },
  {
    prop: "remark",
    label: "备注",
    showOverflowTooltip: true,
  },
  {
    prop: "operation",
    label: "操作",
    width: 100,
    align: "center",
    fixed: "right",
    customSlot: "operation", // 自定义插槽名称
  },
]);
onBeforeUnmount(() => {
  // 卸载组件
  try {
    $uikit.unmount(chat.value);
    $uikit.unmount(conversation.value);
    $uikit.unmount(contactList.value);
    $uikit.unmount(contactInfo.value);
    $uikit.destroy();
  } catch (e) {
    console.log(e);
  }
});
</script>
<style lang="scss" scoped>
.chat-container {
  width: 100%;
  height: 100%;
  box-shadow: 0 0 10px 0 rgba(0, 0, 0, 0.1);
  border-radius: 2px;
  background: #fff;

  .header {
    width: 100%;
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-bottom: 1px solid #e8e8e8;

    .search {
      width: 50%;
    }

    .add {
      margin-left: 20px;
    }
  }

  .content {
    width: 100%;
    height: 100%;
    display: flex;

    .left {
      width: 60px;
      border-right: 1px solid #e8e8e8;
      display: flex;
      flex-direction: column;
      align-items: center;
      position: relative;
      box-sizing: border-box;
      min-width: 60px;
    }

    .right-list {
      width: 300px;
      border-right: 1px solid #e8e8e8;
    }

    .right-content {
      flex: 1;
    }

    .right {
      flex: 1;
      display: flex;

      .chat-info-wrapper {
        background: #fff;
        padding: 10px;
        border-left: 1px solid #e8e8e8;
        width: 400px;
      }
    }

    .collect {
      width: 100%;
      height: 100%;
    }

    .collectRight {
      width: 100%;
      height: 100%;
    }
  }

  :deep(.empty) {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }

  :deep(.chat-header-wrap) {
    height: 60px;
    display: flex;
    align-items: center;
    font-size: 16px;
    border-bottom: 1px solid #dbe0e8;
    padding-left: 16px;
  }

  :deep(.chat-action-wrap) {
    display: none;
  }

  .title {
    position: relative;
    font-weight: bold;
    font-size: 16px;
    padding-left: 10px;

    &:before {
      content: "";
      position: absolute;
      height: 16px;
      background: #4080ff;
      width: 4px;
      left: 0;
      top: 50%;
      transform: translateY(-50%);
    }
  }

  .info {
    display: flex;
    flex-direction: column;
    gap: 6px;
  }

  .info-item {
    display: flex;
    align-items: center;
    font-size: 14px;
    padding: 2px 0;
    white-space: nowrap;
    /* 不换行 */
    overflow: hidden;
    /* 超出隐藏 */
    text-overflow: ellipsis;
    /* 省略号 */
  }

  .label {
    color: #999;
    flex: 0 0 120px;
    /* 固定宽度 */
    text-align: right;
    /* 右对齐 */
    padding-right: 8px;
    /* 添加一点间距 */
  }

  .value {
    color: #333;
    font-weight: 500;
    flex: 1;
    text-align: left;
    /* 内容左对齐 */
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  :deep(.phrases-wrapper) {
    width: 20px;

    .icon {
      width: 23px;
      color: #656a72;
    }
  }
}
</style>
